package service

import (
	"encoding/json"
	"fmt"
	ClickHouse "gin/database"
	"gin/model"
	"gin/types"
	"github.com/gin-gonic/gin"
	teamones_helper "github.com/teamones-open/go-helper"
	"time"
)

type StepCategory struct {
}

// GetStepCategoryList 获取工序分类列表
func (s *StepCategory) GetStepCategoryList(where interface{}) (res []model.StepCategory, err error) {
	err = ClickHouse.DB.Model(&model.StepCategory{}).Where(where).Order("`index` ASC").Find(&res).Error
	return
}

// GetStepCategoryUpstreamDownstreamRelation 查询环节上下游关系
func (s *StepCategory) GetStepCategoryUpstreamDownstreamRelation(ctx *gin.Context, stepCategoryIdList []int64) (res map[int64]types.GetStepCategoryUpstreamDownstreamRelationItem, err error) {
	var tr TeamonesRequest
	var req = map[string]map[string]map[string]interface{}{
		"param": {
			"filter": {
				"id": []interface{}{"-in", stepCategoryIdList},
			},
		},
	}

	reqStr, _ := json.Marshal(req)
	rk := fmt.Sprintf("teamones-saas:step_category/upstream_relation:%s", teamones_helper.GenerateMd5(string(reqStr)))
	err = GetCachedJson(rk, &res)
	if err == nil {
		return
	}
	err = nil
	defer func() {
		_ = SetCacheJsonExpire(rk, &res, time.Minute*3)
	}()
	var headers = map[string]string{"x-userinfo": GetStringFromContext(ctx, "x-userinfo")}
	var qRes types.GetStepCategoryUpstreamDownstreamRelationRes
	err = tr.Do("teamones-saas", "step_category/upstream_relation", req, headers, &qRes)
	if err != nil {
		return
	}
	res = make(map[int64]types.GetStepCategoryUpstreamDownstreamRelationItem)
	for _, datum := range qRes.Data {
		res[datum.Id] = datum
	}

	return
}
